home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 4 / Apprentice-Release4.iso / Languages / Caml Light 0.7 / examples / basics / wc.ml < prev   
Text File  |  1995-06-10  |  1KB  |  61 lines

  1. (* Counts characters, lines and words in one or several files. *)
  2.  
  3. let chars = ref 0
  4. and words = ref 0
  5. and lines = ref 0
  6. ;;
  7.  
  8. type state = Inside_word | Outside_word;;
  9.  
  10. let count_channel in_channel =
  11.   let rec count status =
  12.     let c = input_char in_channel in
  13.     incr chars;
  14.     match c with
  15.       `\n` ->
  16.         incr lines; count Outside_word
  17.     | ` ` | `\t` ->
  18.         count Outside_word
  19.     | _ ->
  20.         if status = Outside_word then begin incr words; () end;
  21.         count Inside_word
  22.   in
  23.     try
  24.       count Outside_word
  25.     with End_of_file ->
  26.       ()
  27. ;;
  28.  
  29. let count_file name =
  30.   let ic = open_in name in
  31.   count_channel ic;
  32.   close_in ic
  33. ;;
  34.  
  35. let print_result () =
  36.   print_int !chars; print_string " characters, ";
  37.   print_int !words; print_string " words, ";
  38.   print_int !lines; print_string " lines";
  39.   print_newline()
  40. ;;
  41.  
  42. let count name =
  43.   count_file name;
  44.   print_result ()
  45. ;;  
  46.  
  47. if sys__interactive then () else
  48. try
  49.   if vect_length sys__command_line <= 1 then
  50.     count_channel std_in                (* No command-line arguments *)
  51.   else
  52.     for i = 1 to vect_length sys__command_line - 1 do
  53.       count_file  sys__command_line.(i)
  54.     done;
  55.   print_result ();
  56. with sys__Sys_error s ->
  57.   print_string "I/O error: ";
  58.   print_string s;
  59.   print_newline()
  60. ;;
  61.